package hello.app.dialog;

import hello.app.R;
import hello.app.model.CommentModel;
import hello.app.model.HelloApi;
import hello.app.model.ModelManager;
import hello.app.model.data.Comment;
import hello.app.util.AdteAsyncTask;
import hello.app.util.AdteAsyncTask.BackgroundRunner;
import hello.app.util.AdteAsyncTask.FinishRunner;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;

public class CommentEvaluationBuilder extends Builder implements DialogInterface.OnClickListener, FinishRunner{

	private ModelManager mModelManager;
	private Comment mComment;
	private OnFinishListener mFinish;

	public interface OnFinishListener{
		public void onFinished(boolean success);
	}

	class GoodRunner implements BackgroundRunner{
		HelloApi mApi;
		CommentModel mModel;

		public GoodRunner(HelloApi api, CommentModel model){
			mApi = api;
			mModel = model;
		}

		public Object exec(Object... args) {
			Comment cmt = (Comment)args[0];
			try {
				cmt = mApi.addGoodCommentCount(cmt.getId().intValue());
				mModel.save(cmt);
			} catch (Exception e) {
				return false;
			}
			return true;
		}
	}

	class BadRunner implements BackgroundRunner{
		HelloApi mApi;
		CommentModel mModel;

		public BadRunner(HelloApi api, CommentModel model){
			mApi = api;
			mModel = model;
		}

		public Object exec(Object... args) {
			Comment cmt = (Comment)args[0];
			try {
				cmt = mApi.addBadCommentCount(cmt.getId().intValue());
				mModel.save(cmt);
			} catch (Exception e) {
				return false;
			}
			return true;
		}
	}

	public CommentEvaluationBuilder(Context context, Comment comment) {
		super(context);
		mComment = comment;
		mModelManager = ModelManager.getInstatce(context);
		setIcon(android.R.drawable.btn_star);
		setTitle("コメントの評価");
		setMessage("コメントを評価を変更してください");
		setPositiveButton(context.getString(R.string.good), this);
		setNegativeButton(context.getString(R.string.bad), this);
		setNeutralButton(context.getString(R.string.neutral), this);

	}

	public void setOnFinishListener(OnFinishListener listener){
		mFinish = listener;
	}

	public void onClick(DialogInterface dialog, int which) {
		HelloApi api = mModelManager.getHelloApi();
		CommentModel model = mModelManager.getCommentModel();
		AdteAsyncTask task = new AdteAsyncTask();
		task.setPostRunner(this);
		task.setDelayTime(500);
		switch(which){
		case DialogInterface.BUTTON_POSITIVE:
			task.setBackgroundRunner(new GoodRunner(api,model));
			break;
		case DialogInterface.BUTTON_NEGATIVE:
			task.setBackgroundRunner(new BadRunner(api,model));
			break;
		case DialogInterface.BUTTON_NEUTRAL:
		default:
			return;
		}
		task.execute(mComment);
	}

	public void onFinish(Object success) {
		if(mFinish != null){
			mFinish.onFinished((Boolean)success);
		}
	}
}
